/*
 *    Copyright (c) 2018-2025, boss All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the boss developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: boss
 */

package com.hopes.bizz.basic.hazard.sds.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hopes.bizz.basic.hazard.sds.bo.HazChemicalComponentBO;
import com.hopes.bizz.basic.hazard.sds.dto.HazChemicalSdsDTO;
import com.hopes.bizz.basic.hazard.sds.dto.HazChemicalSdsExcelDTO;
import com.hopes.bizz.basic.hazard.sds.entity.*;
import com.hopes.bizz.basic.hazard.sds.service.*;
import com.hopes.bizz.basic.hazard.sds.vo.HazChemicalSdsExcelVO;
import com.hopes.bizz.basic.hazard.sds.vo.HazChemicalSdsVO;
import com.hopes.boss.common.core.util.R;
import com.hopes.boss.common.excel.annotation.RequestExcel;
import com.hopes.boss.common.excel.annotation.ResponseExcel;
import com.hopes.boss.common.log.annotation.SysLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 企业危险化学品SDS
 *
 * @author daijie
 * @date 2023-11-13 11:10:15
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/sds")
@Tag(description = "sds", name = "企业危险化学品SDS管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class HazChemicalSdsController {

    private final HazChemicalSdsService hazChemicalSdsService;
    private final HazChemicalStockService hazChemicalStockService;
    private final HazChemicalInService hazChemicalInService;
    private final HazChemicalOutService hazChemicalOutService;
    private final HazChemicalComponentService hazChemicalComponentService;

    /**
     * 分页查询
     *
     * @param page           分页对象
     * @param hazChemicalSds 企业危险化学品SDS
     * @return
     */
    @Operation(summary = "分页查询", description = "分页查询")
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('haz_sds_view')")
    public R gethazChemicalSdsPage(Page page, HazChemicalSdsEntity hazChemicalSds) {
        LambdaQueryWrapper<HazChemicalSdsEntity> wrapper = Wrappers.lambdaQuery();
        if (ObjectUtils.isNotNull(hazChemicalSds.getSdsCode())) {
            String sdsCode = hazChemicalSds.getSdsCode();
            wrapper.like(HazChemicalSdsEntity::getName, sdsCode).or()
                            .like(HazChemicalSdsEntity::getSdsCode, sdsCode).or()
                            .like(HazChemicalSdsEntity::getCasNo, sdsCode);
        }
        wrapper.eq(ObjectUtils.isNotNull(hazChemicalSds.getKeyFlag()), HazChemicalSdsEntity::getKeyFlag, hazChemicalSds.getKeyFlag());
        wrapper.eq(ObjectUtils.isNotNull(hazChemicalSds.getSpecialFlag()), HazChemicalSdsEntity::getSpecialFlag, hazChemicalSds.getSpecialFlag());
        wrapper.eq(ObjectUtils.isNotNull(hazChemicalSds.getChemicalType()), HazChemicalSdsEntity::getChemicalType, hazChemicalSds.getChemicalType());
        wrapper.eq(ObjectUtils.isNotNull(hazChemicalSds.getOrgId()), HazChemicalSdsEntity::getOrgId, hazChemicalSds.getOrgId());

        Page<HazChemicalSdsEntity> sdsPage = hazChemicalSdsService.page(page, wrapper);
        List<HazChemicalSdsVO> voList = new ArrayList<>();
        Page<HazChemicalSdsVO> voPage = new Page<>(sdsPage.getCurrent(), sdsPage.getSize(), sdsPage.getTotal(), sdsPage.searchCount());
        voPage.setRecords(voList);

        for (HazChemicalSdsEntity record : sdsPage.getRecords()) {
            HazChemicalSdsVO vo = new HazChemicalSdsVO();
            BeanUtils.copyProperties(record, vo);

            List<HazChemicalComponentEntity> componentList = hazChemicalComponentService.list(Wrappers.lambdaQuery(HazChemicalComponentEntity.class)
                    .eq(HazChemicalComponentEntity::getSdsId, record.getId()));
            vo.setComponentList(componentList);
            voList.add(vo);
        }
        return R.ok(voPage);
    }

    /**
     * 分页查询库存统计
     *
     * @param page           分页对象
     * @param hazChemicalSds 企业危险化学品SDS
     * @return
     */
    @Operation(summary = "分页查询库存统计", description = "分页查询库存统计")
    @GetMapping("/stockPage")
    @PreAuthorize("@pms.hasPermission('haz_sds_view')")
    public R stockPage(Page page, HazChemicalSdsEntity hazChemicalSds) {
        return R.ok(hazChemicalSdsService.stockPage(page, hazChemicalSds));
    }


    /**
     * 通过id查询企业危险化学品SDS
     *
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询", description = "通过id查询")
    @GetMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('haz_sds_view')")
    public R getById(@PathVariable("id") Long id) {
        HazChemicalSdsEntity entity = hazChemicalSdsService.getById(id);
        HazChemicalSdsVO vo = new HazChemicalSdsVO();
        BeanUtils.copyProperties(entity, vo);

        List<HazChemicalComponentEntity> componentList = hazChemicalComponentService.list(Wrappers.lambdaQuery(HazChemicalComponentEntity.class)
                .eq(HazChemicalComponentEntity::getSdsId, id));
        vo.setComponentList(componentList);
        return R.ok(vo);
    }

    /**
     * 新增企业危险化学品SDS
     *
     * @param hazChemicalSds 企业危险化学品SDS
     * @return R
     */
    @Operation(summary = "新增企业危险化学品SDS", description = "新增企业危险化学品SDS")
    @SysLog("新增企业危险化学品SDS")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('haz_sds_add')")
    @Transactional(rollbackFor = Exception.class)
    public R save(@RequestBody HazChemicalSdsDTO hazChemicalSds) {
        hazChemicalSdsService.save(hazChemicalSds);

        for (HazChemicalComponentBO hazChemicalComponentBO : hazChemicalSds.getComponentList()) {
            HazChemicalComponentEntity componentEntity = new HazChemicalComponentEntity();
            BeanUtils.copyProperties(hazChemicalComponentBO, componentEntity);
            componentEntity.setSdsId(hazChemicalSds.getId());

            hazChemicalComponentService.save(componentEntity);
        }

        return R.ok();
    }

    /**
     * 修改企业危险化学品SDS
     *
     * @param hazChemicalSds 企业危险化学品SDS
     * @return R
     */
    @Operation(summary = "修改企业危险化学品SDS", description = "修改企业危险化学品SDS")
    @SysLog("修改企业危险化学品SDS")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('haz_sds_edit')")
    @Transactional(rollbackFor = Exception.class)
    public R updateById(@RequestBody HazChemicalSdsDTO hazChemicalSds) {
        hazChemicalSdsService.updateById(hazChemicalSds);

        hazChemicalComponentService.remove(Wrappers.lambdaQuery(HazChemicalComponentEntity.class)
                .eq(HazChemicalComponentEntity::getSdsId, hazChemicalSds.getId()));

        for (HazChemicalComponentBO hazChemicalComponentBO : hazChemicalSds.getComponentList()) {
            HazChemicalComponentEntity componentEntity = new HazChemicalComponentEntity();
            BeanUtils.copyProperties(hazChemicalComponentBO, componentEntity);
            componentEntity.setSdsId(hazChemicalSds.getId());

            hazChemicalComponentService.save(componentEntity);
        }
        return R.ok();
    }

    /**
     * 通过id删除企业危险化学品SDS
     *
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除企业危险化学品SDS", description = "通过id删除企业危险化学品SDS")
    @SysLog("通过id删除企业危险化学品SDS")
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('haz_sds_del')")
    @Transactional(rollbackFor = Exception.class)
    public R removeById(@RequestBody Long[] ids) {
        hazChemicalSdsService.removeBatchByIds(CollUtil.toList(ids));

        // 关联删除
        hazChemicalStockService.remove(Wrappers.lambdaQuery(HazChemicalStockEntity.class)
                .in(HazChemicalStockEntity::getSdsId, CollUtil.toList(ids)));
        hazChemicalInService.remove(Wrappers.lambdaQuery(HazChemicalInEntity.class)
                .in(HazChemicalInEntity::getSdsId, CollUtil.toList(ids)));
        hazChemicalOutService.remove(Wrappers.lambdaQuery(HazChemicalOutEntity.class)
                .in(HazChemicalOutEntity::getChemicalId, CollUtil.toList(ids)));

        return R.ok();
    }

    /**
     * excel模板
     *
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/template")
    @PreAuthorize("@pms.hasPermission('haz_sds_export')")
    public List<HazChemicalSdsExcelVO> template() {
        return hazChemicalSdsService.exportExcel(Arrays.asList(new HazChemicalSdsEntity()));
    }

    /**
     * 导出excel 表格
     *
     * @param hazChemicalSds 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('haz_sds_export')")
    public List<HazChemicalSdsExcelVO> export(HazChemicalSdsEntity hazChemicalSds) {
        LambdaQueryWrapper<HazChemicalSdsEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ObjectUtils.isNotNull(hazChemicalSds.getSpecialFlag()), HazChemicalSdsEntity::getSpecialFlag, hazChemicalSds.getSpecialFlag());
        wrapper.eq(ObjectUtils.isNotNull(hazChemicalSds.getKeyFlag()), HazChemicalSdsEntity::getKeyFlag, hazChemicalSds.getKeyFlag());
        wrapper.eq(ObjectUtils.isNotNull(hazChemicalSds.getChemicalType()), HazChemicalSdsEntity::getChemicalType, hazChemicalSds.getChemicalType());
        if (ObjectUtils.isNotNull(hazChemicalSds.getSdsCode())) {
            String sdsCode = hazChemicalSds.getSdsCode();
            wrapper.like(HazChemicalSdsEntity::getName, sdsCode).or()
                    .like(HazChemicalSdsEntity::getSdsCode, sdsCode).or()
                    .like(HazChemicalSdsEntity::getCasNo, sdsCode);
        }

        return hazChemicalSdsService.exportExcel(hazChemicalSdsService.list(wrapper));
    }

    /**
     * 导入excel 表格
     *
     * @param hazChemicalSdsExcelDtoList 查询条件
     * @param bindingResult              错误信息列表
     * @return ok fail
     */
    @PostMapping("/import")
    @PreAuthorize("@pms.hasPermission('haz_sds_export')")
    public R importExcel(@RequestExcel List<HazChemicalSdsExcelDTO> hazChemicalSdsExcelDtoList, BindingResult bindingResult) {
        return hazChemicalSdsService.importExcel(hazChemicalSdsExcelDtoList, bindingResult);
    }

}
